package bainuo

import com.alibaba.fastjson.JSON

def execute(data, dlzt) {
    println "-------------------------调用服务接口-------------------------"
    def items = data.get("items")
    def mtrlNo = items.get("mtrlNo")
    def mtrlName = items.get("mtrlName")
    def mtrlSpec = items.get("mtrlSpec")
    def mtrlRefno = items.get("mtrlRefno")
    def unitId = items.get("unitId")
    def purwayId = items.get("purwayId")
    def mtrlTaxrate = items.get("mtrlTaxrate")
    def mtrlProperty = items.get("mtrlProperty")
    def mtrlType = items.get("mtrlType")
    def mtrlIsnew = items.get("mtrlIsnew")
    def mtrlFeature = items.get("mtrlFeature")
    def mtrlDrawingno = items.get("mtrlDrawingno")
    def mtrlClass = items.get("mtrlClass")
    def mtrlCateid = items.get("mtrlCateid")
    def mtrlBrandmark = items.get("mtrlBrandmark")
    def cas = items.get("cas")
    def lowLimitWarningValue = items.get("lowLimitWarningValue")
    def fNote = items.get("fNote")
//    mtrlNo	物料代码
//    mtrlName	物料名称
//    mtrlSpec	规格型号
//    mtrlRefno	参照编号
//    unitId	计量单位
//    purwayId	采购方式
//    mtrlTaxrate	税率
//    mtrlProperty	物料属性
//    mtrlType	供应形态
//    mtrlIsnew	编码标识
//    mtrlFeature	特征描述
//    mtrlDrawingno	物料图号
//    mtrlClass	物料类别
//    mtrlCateid	物料类别编码
//    mtrlBrandmark	商标牌号
//    cas	CAS
//    lowLimitWarningValue	库存警戒线
//    fNote	备注

    try {
        //请求信息
        if (wareHouseNo == null) {
            return ["state": 0, "Ascript": "缺少物料代码(mtrlNo) 请求JSON" + data]
        }
        if (wareHouseName == null) {
            return ["state": 0, "Ascript": "缺少物料名称(mtrlName) 请求JSON" + data]
        }
        def reMap = TransVoucherOpenApi_Create(data, dlzt)
        println "返回信息"
        println reMap
        if (reMap.get("state") == 1) {
            return ["state": 1, "Ascript": reMap.get("Ascript"), "data": reMap.get("data")]
        } else {
            return ["state": 0, "Ascript": reMap.get("Ascript")]
        }

    } catch (Exception e) {
        e.printStackTrace();
        return ["state": 0, "Ascript": "请求参数错误,请检查"]
    }

}

def TransVoucherOpenApi_Create(data, dlzt) {
    try {
        def headUpMap = data.get("head")
        if (headUpMap == null || headUpMap.size() == 0) {
            return ["state": 0, "Ascript": "请求参数中表头不能为空"]
        }
        def headMap = [:]

        def bodyUpList = data.get("items")
        if (bodyUpList == null || bodyUpList.size() == 0) {
            return ["state": 0, "Ascript": "请求参数中表体不能为空"]
        }
        def bodyList = []
        //时间
        java.text.SimpleDateFormat dqdate = new java.text.SimpleDateFormat("yyyy-MM-dd")
        def dqdateString = dqdate.format(new Date())
        java.text.SimpleDateFormat dqdatetime = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        def dqdatetimeString = dqdatetime.format(new Date())


        def items = ["items": [:]]

        //表体结构
        def RDRecordDetails = []
        //表体参数循环赋值
        for (int i = 0; i < bodyList.size(); i++) {
            def bodyMap = bodyList.get(i)
            if (bodyMap == null || bodyMap.size() == 0) {
                return ["state": 0, "Ascript": "表体数据不能为空"]
            }
            def BodyToObject = ["wareHouseNo":"货位编号", "wareHouseName":"货位名称", "parentNo":"上级仓库编号", "parentName":"上级仓库名称", "storeKeeperName":"保管员名称", "wareHouseType":"货位类型", "remark":"备注"]
            for (def key : BodyToObject.keySet()) {
                if (bodyMap.get(key) != null) {
                    bodyMap.put(key, ["code": bodyMap.get(key)])
                }
            }
        }

        RDRecordDetails.addAll(bodyList)
        items.get("items").put("RDRecordDetails", RDRecordDetails)
        def reMap = HQMHttps.httpFWToMap("http://10.1.1.79/api/module/bn/wm/warehouseitem", items)
        if ("0".equals(reMap.get("code").toString())) {
            return ["state": 1, "Ascript": "操作成功,单据号为：" + reMap.get("data").get("Code"), "data": reMap.get("data")]
        } else {
            return ["state": 0, "Ascript": reMap.get("message") + "错误码为:" + reMap.get("code") + "   错误回答为" + reMap.get("data")]
        }
    }catch (Exception e) {
        e.printStackTrace();
        return ["state": 0, "Ascript": "操作错误"]
    }
}

class HQMHttps {
    public static HashMap<String, Object> account = new HashMap<String, Object>();

    public HQMHttps() {
    }

    public HQMHttps(HashMap<String, Object> account) {
        this.account = account;
    }
    //进行Http请求
    public static List httpFWToList(String url, Map mapdata) {
        String json = JSON.toJSONString(mapdata);
        //        println "请求JSON"
        //        println json
        //PrintWriter out = null;
        DataOutputStream out
        BufferedReader ins = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            HttpURLConnection conn = realUrl.openConnection();
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            conn.setUseCaches(false);
            conn.setInstanceFollowRedirects(true);
            // 设置通用的请求属性
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Transfer-Encoding", "chunked");
            conn.setRequestProperty("Keep-Alive", "chunked");
            conn.setRequestProperty("ClientId", "bnyy.esb.biz.bip");
            conn.setRequestProperty("OperationCode", "bnyy.esb.biz.wms.warehouse.api");
            conn.setRequestProperty("LoginCode", "sysadmin");
            conn.setRequestProperty("LoginPassword", "000000");
            conn.connect();
            // 获取HttpURLConnection对象对应的输出流
            //            out = new PrintWriter(conn.getOutputStream());
            //            // 发送请求参数
            //            out.print(json);
            //            // flush输出流的缓冲
            //            out.flush();
            out = new DataOutputStream(conn.getOutputStream());
            if (!"".equals(json)) {
                //out.writeBytes(json);
                out.write(json.getBytes("UTF-8"));
            }
            out.flush();
            out.close();

            // 定义BufferedReader输入流来读取URL的响应
            //ins = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            if (conn.getResponseCode() == 200) {
                ins = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            } else {
                ins = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
            }
            String line;
            while ((line = ins.readLine()) != null) {
                result += line;
            }
            return JSON.parseObject(result, List.class);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e);
            System.out.println("[POST请求]向地址：" + url + " 发送数据：" + json + " 发生错误!" + result + "JSON结束");
        } finally {// 使用finally块来关闭输出流、输入流
            try {
                if (out != null) {
                    out.close();
                }
                if (ins != null) {
                    ins.close();
                }
            } catch (IOException ex) {
                System.out.println("关闭流异常");
            }
        }
        return null;
    }
    //进行Http请求
    public static Map httpFWToMap(String url, Map mapdata) {
        String json = JSON.toJSONString(mapdata);
        println "请求JSON"
        println json
        //PrintWriter out = null;
        DataOutputStream out
        BufferedReader ins = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            HttpURLConnection conn = realUrl.openConnection();
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            conn.setUseCaches(false);
            conn.setInstanceFollowRedirects(true);
            // 设置通用的请求属性
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Transfer-Encoding", "chunked");
            conn.setRequestProperty("Keep-Alive", "chunked");
            conn.setRequestProperty("ClientId", "bnyy.esb.biz.bip");
            conn.setRequestProperty("OperationCode", "bnyy.esb.biz.wms.warehouse.api");
            conn.setRequestProperty("LoginCode", "sysadmin");
            conn.setRequestProperty("LoginPassword", "000000");
            conn.connect();
            // 获取HttpURLConnection对象对应的输出流
            //            out = new PrintWriter(conn.getOutputStream());
            //            // 发送请求参数
            //            out.print(json);
            //            // flush输出流的缓冲
            //            out.flush();
            out = new DataOutputStream(conn.getOutputStream());
            if (!"".equals(json)) {
                //out.writeBytes(json);
                out.write(json.getBytes("UTF-8"));
            }
            out.flush();
            out.close();


            // 定义BufferedReader输入流来读取URL的响应
            //            ins = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            if (conn.getResponseCode() == 200) {
                ins = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            } else {
                ins = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
            }

            String line;
            while ((line = ins.readLine()) != null) {
                result += line;
            }
            return JSON.parseObject(result, Map.class);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("[POST请求]向地址：" + url + " 发送数据：" + json + " 发生错误!" + result + "JSON结束");
        } finally {// 使用finally块来关闭输出流、输入流
            try {
                if (out != null) {
                    out.close();
                }
                if (ins != null) {
                    ins.close();
                }
            } catch (IOException ex) {
                System.out.println("关闭流异常");
            }
        }
        return null;
    }

    public static String httpFWToJson(String url, Map mapdata) {
        String json = JSON.toJSONString(mapdata);
        //        println "请求JSON"
        //        println json
        //PrintWriter out = null;
        DataOutputStream out
        BufferedReader ins = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            HttpURLConnection conn = realUrl.openConnection();
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            conn.setUseCaches(false);
            conn.setInstanceFollowRedirects(true);
            // 设置通用的请求属性
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Transfer-Encoding", "chunked");
            conn.setRequestProperty("Keep-Alive", "chunked");
            conn.setRequestProperty("ClientId", "bnyy.esb.biz.bip");
            conn.setRequestProperty("OperationCode", "bnyy.esb.biz.wms.warehouse.api");
            conn.setRequestProperty("LoginCode", "sysadmin");
            conn.setRequestProperty("LoginPassword", "000000");
            conn.connect();
            // 获取HttpURLConnection对象对应的输出流
            //            out = new PrintWriter(conn.getOutputStream());
            //            // 发送请求参数
            //            out.print(json);
            //            // flush输出流的缓冲
            //            out.flush();
            out = new DataOutputStream(conn.getOutputStream());
            if (!"".equals(json)) {
                //out.writeBytes(json);
                out.write(json.getBytes("UTF-8"));
            }
            out.flush();
            out.close();

            // 定义BufferedReader输入流来读取URL的响应
            //            ins = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            if (conn.getResponseCode() == 200) {
                ins = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            } else {
                ins = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
            }
            String line;
            while ((line = ins.readLine()) != null) {
                result += line;
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("[POST请求]向地址：" + url + " 发送数据：" + json + " 发生错误!" + result + "JSON结束");
        } finally {// 使用finally块来关闭输出流、输入流
            try {
                if (out != null) {
                    out.close();
                }
                if (ins != null) {
                    ins.close();
                }
            } catch (IOException ex) {
                System.out.println("关闭流异常");
            }
        }
        return null;
    }
}